<template>
  <view class="navbar" :class="{ 'navbar-scrolled': scrolled }">
    <view class="statusBar" :style="{ height: getStatusBarHeight() + 'px' }"></view>
    <view class="titleBar" :style="{ height: getTitleBarHeight() + 'px', marginLeft: getLeftIconLeft() + 'px' }">
      <view class="item">
        <uni-icons type="left" size="25" class="animated-icon" @click="goBack"></uni-icons>
        <text class="title-text">AI找书</text>
        <uni-icons type="trash" size="25" class="animated-icon" @click="clearHistory"></uni-icons>
      </view>
    </view>
  </view>

  <view class="fill" :style="{ height: getNavBarHeight() + 'px' }"></view>

  <view class="gradient-bg" ref="gradientRef">
    <view v-show="!isInConversation" class="book-assistant" :class="{ 'fade-in': showAssistant }">
      <text class="main-text">叮！我是AI找书小助手</text>
      <text class="sub-text">可以帮你寻找感兴趣的作品，快来提问吧</text>
    </view>

    <view v-show="!isInConversation" class="recommend-section">
      <view class="refresh-bar">
        <text class="refresh-label">你可以这样问</text>
        <view class="refresh-btn" @click="refreshQuestions">
          <uni-icons type="reload" size="20" style="vertical-align: middle;" :class="{ 'rotate-animation': isRefreshing }"></uni-icons>
          换一换
        </view>
      </view>
      <view class="question-grid">
        <view
          class="question-card"
          v-for="(question, idx) in displayQuestions"
          :key="idx"
          :class="{ 'animate-in': shouldAnimate(idx) }"
          :style="{ animationDelay: (idx * 100) + 'ms' }"
          @click="handleQuestion(question)"
        >
          {{ question }}
        </view>
      </view>
    </view>

    <view class="dig">
      <scroll-view
        scroll-y
        class="chat-container"
        :scroll-into-view="'msg-' + chatMessages.length"
        :scroll-top="scrollTop"
      >
        <view class="chat-box" ref="chatBox">
          <view
            v-for="(msg, idx) in chatMessages"
            :key="idx"
            class="chat-item"
            :class="{ 'user-msg': msg.type === 'user', 'ai-msg': msg.type === 'ai' }"
            :id="'msg-' + idx"
          >
            <view class="msg-content">{{ msg.content }}</view>
          </view>
          <!-- 添加一个辅助元素，用于滚动到底部 -->
          <view :id="'msg-' + chatMessages.length" style="height: 0; width: 0;"></view>
        </view>
      </scroll-view>
    </view>
  </view>

  <view class="bottom-input">
    <view class="input-container">
      <input
        type="text"
        v-model="userInput"
        placeholder="请输入您想要查找的书籍或关键词..."
        class="input-field"
        @focus="handleInputFocus"
        @blur="handleInputBlur"
        @input="handleInput"
      />
      <view
        class="send-btn"
        :class="{ 'btn-active': userInput.trim().length > 0 }"
        @click="sendMessage"
        :style="{ cursor: userInput.trim().length > 0 ? 'pointer' : 'not-allowed' }"
      >
        <uni-icons type="send" size="22" />
        <text class="send-text">发送</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIconLeft } from "@/utils/system.js";
import { ApiClearCache, ApiAiSearch } from '../api/novel';

const gradientRef = ref(null);
const scrolled = ref(false);
const showAssistant = ref(false);
const animationTrigger = ref(0);
const refreshing = ref(false);
const userInput = ref('');
const inputFocused = ref(false);
const isRefreshing = ref(false);
const isInConversation = ref(false);
const chatMessages = ref([]);
const scrollTop = ref(0);
const chatBox = ref(null);
const isThinking = ref(false); // 是否正在思考
const thinkingText = ref(''); // 思考中的文字
const thinkingTimer = ref(null); // 思考中的定时器
const thinkingDots = ref(0); // 思考中的点的数量

// 推荐问题数据
const allQuestions = [
  [
    "推荐一些结合赛博朋克、克苏鲁与末日元素的作品",
    "推荐几本克苏鲁风都市怪谈文",
    "推荐主角开武馆的武侠文，口碑好的",
    "推荐一些三国背景的小说，主角有能力改变历史走向的",
    "字数200万以上的都市异能文，首订过万",
    "推荐西方魔幻类小说，主角是魔法师的",
    "有没有主角拥有特殊能力的现代修真小说"
  ],
  [
    "推荐类似《三体》的硬核科幻小说",
    "有没有主角重生到古代搞发明的小说",
    "推荐几本悬疑推理类的短篇小说集",
    "求高质量的历史架空小说，文笔要好",
    "推荐一些轻松搞笑的都市异能小说",
    "推荐以二战为背景的历史小说",
    "求好看的快穿文，系统流的"
  ],
  [
    "推荐主角从底层崛起的玄幻小说",
    "推荐现代修真类小说，主角低调发展的",
    "有没有主角穿越到动漫世界的小学",
    "推荐一些女主很强势的言情小说",
    "求武侠类小说，主角有独特武功的",
    "推荐末世废土类小说，有基地建设的",
    "推荐一些高智商博弈的悬疑小说"
  ]
];

let currentQuestionSet = 0;
const currentQuestions = ref(allQuestions[currentQuestionSet]);
const displayQuestions = computed(() => currentQuestions.value.slice(0, 4));

// 导航栏滚动处理
const handleScroll = () => {
  scrolled.value = window.scrollY > 10;
};

// 背景视差处理
const handleMouseMove = (e) => {
  if (gradientRef.value?.style) {
    const x = (window.innerWidth - e.pageX * 2) / 90;
    const y = (window.innerHeight - e.pageY * 2) / 90;
    gradientRef.value.style.transform = `translateX(${x}px) translateY(${y}px)`;
  }
};

// 问题动画判断
const shouldAnimate = (index) => {
  return animationTrigger.value === 0 || (refreshing.value && animationTrigger.value > 0);
};

// 刷新推荐问题
const refreshQuestions = () => {
  isRefreshing.value = true;
  currentQuestionSet = (currentQuestionSet + 1) % allQuestions.length;
  currentQuestions.value = allQuestions[currentQuestionSet];
  animationTrigger.value++;
  setTimeout(() => {
    isRefreshing.value = false;
  }, 500);
};

// 推荐问题点击处理
const handleQuestion = (q) => {
  userInput.value = q;
};

// 输入框焦点处理
const handleInputFocus = () => {
  inputFocused.value = true;
};

const handleInputBlur = () => {
  inputFocused.value = false;
};

// 处理输入事件
const handleInput = () => {
  // 在这里处理输入事件，如果需要
};

// 发送消息处理
const sendMessage = async () => {
  if (userInput.value.trim().length === 0) return;

  chatMessages.value.push({ type: 'user', content: userInput.value });
  isInConversation.value = true;

  const temp = userInput.value;
  userInput.value = '';

  // 用户发送消息后滚动到底部
  nextTick(() => {
    scrollToBottom();
  });

  // 显示“思考中...”动画
  isThinking.value = true;
  thinkingText.value = '思考中';
  thinkingDots.value = 0;
  thinkingTimer.value = setInterval(() => {
    thinkingDots.value = (thinkingDots.value + 1) % 4;
    thinkingText.value = '思考中' + '.'.repeat(thinkingDots.value);
  }, 500);

  // 添加思考中的消息
  chatMessages.value.push({ type: 'ai', content: thinkingText.value });

  // 模拟AI流式输出
  const response = await ApiAiSearch(temp);
  let aiMessage = '';
  for (let i = 0; i < response.length; i++) {
    aiMessage += response[i];
    // 更新AI消息
    chatMessages.value[chatMessages.value.length - 1].content = aiMessage;
    await new Promise(resolve => setTimeout(resolve, 50)); // 模拟流式输出的速度
  }

  // 隐藏“思考中...”动画
  clearInterval(thinkingTimer.value);
  isThinking.value = false;

  // 更新为完整的AI消息
  chatMessages.value[chatMessages.value.length - 1].content = response;

  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });
};

// 滚动到底部的函数
const scrollToBottom = () => {
  if (chatBox.value) {
    const lastMessageId = 'msg-' + (chatMessages.value.length - 1);
    const lastMessageElement = document.getElementById(lastMessageId);
    if (lastMessageElement) {
      lastMessageElement.scrollIntoView({ behavior: 'smooth', block: 'end' });
    }
  }
};

// 清空历史记录 - 添加确认提示
const clearHistory = async () => {
  // 显示确认对话框
  uni.showModal({
    title: '确认清空',
    content: '确定要清空所有聊天记录吗？此操作不可恢复。',
    confirmText: '确认',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        // 用户点击确认，执行清空操作
        chatMessages.value = [];
        isInConversation.value = false;
        await ApiClearCache();
        
        // 显示成功提示
        uni.showToast({
          title: '历史记录已清空',
          icon: 'success',
          duration: 1500
        });
      } else if (res.cancel) {
        // 用户点击取消，不执行任何操作
        console.log('用户取消清空');
      }
    }
  });
};

// 生命周期钩子
onMounted(() => {
  window.addEventListener('scroll', handleScroll);
  window.addEventListener('mousemove', handleMouseMove);

  setTimeout(() => {
    showAssistant.value = true;
    setTimeout(() => {
      animationTrigger.value++;
    }, 500);
  }, 300);
});

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll);
  window.removeEventListener('mousemove', handleMouseMove);
});

// 返回
const goBack = () => {
  uni.navigateBack();
};
</script>

<style lang="less" scoped>
/* 基础样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Inter', sans-serif;
}

body, html {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

/* 导航栏样式 */
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 10;
  background: #e6f3ff;
  transition: all 0.3s ease;

  &.navbar-scrolled {
    background: rgba(230, 243, 255, 0.95);
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  }

  .titleBar {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 30rpx;
    transition: transform 0.3s ease;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
    }

    .title-text {
      font-size: 20px;
      font-weight: 600;
      background-image: linear-gradient(45deg, #4a90e2, #9b59b6);
      background-clip: text;
      -webkit-background-clip: text;
      color: transparent;
      transition: all 0.3s ease;

      &:hover {
        transform: scale(1.05);
      }
    }
  }

  .statusBar {
    background-color: #e6f3ff;
  }
}

/* 图标悬停动画 */
.animated-icon {
  transition: transform 0.3s ease;

  &:hover {
    transform: scale(1.2);
  }
}

/* 填充区域 */
.fill {
  background: transparent;
}

/* AI助手提示区域 */
.book-assistant {
  padding-top: 20px;
  margin: 0 20px;
  padding: 40rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.5s ease;

  &.fade-in {
    opacity: 1;
    transform: translateY(0);
  }

  .main-text {
    font-size: 32rpx;
    font-weight: 600;
    color: #1a1a1a;
    display: block;
    margin-bottom: 15rpx;
  }

  .sub-text {
    font-size: 28rpx;
    color: #666;
    line-height: 40rpx;
  }
}

/* 渐变背景区域 */
.gradient-bg {
  padding-top: 20px;
  padding-bottom: 140rpx;
  background: linear-gradient(135deg, #e6f3ff, #f0f2f5);
  transition: all 0.5s ease;
  position: relative;
  overflow: visible;
  min-height: calc(100vh - var(--window-bottom));
  height: calc(100vh - var(--window-bottom));
}

/* 推荐问题区域 */
.recommend-section {
  padding: 30rpx;
  position: relative;
  z-index: 1;

  .refresh-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30rpx;

    .refresh-label {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }

    .refresh-btn {
      display: flex;
      align-items: center;
      gap: 10rpx;
      font-size: 28rpx;
      color: #666;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #4a90e2;
      }
    }
  }

  .question-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300rpx, 1fr));
    gap: 30rpx;
  }

  .question-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx 40rpx;
    margin-bottom: 0;
    font-size: 28rpx;
    color: #333;
    cursor: pointer;
    line-height: 1.6;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

    &:hover {
      transform: translateY(-4rpx);
      box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.15);
    }

    /* 入场动画 */
    &.animate-in {
      opacity: 0;
      transform: translateX(-20px);
      animation: fadeInFromLeft 0.8s forwards cubic-bezier(0.22, 1, 0.36, 1);
    }
  }

  @keyframes fadeInFromLeft {
    from { opacity: 0; transform: translateX(-20px); }
    to { opacity: 1; transform: translateX(0); }
  }
}

/* 对话区域 */
.dig {
  padding: 20rpx;
  padding-bottom: 120rpx; /* 增加底部间距，避免被底部输入框遮挡 */
}

.chat-container {
  min-height: 300rpx;
  max-height: calc(100vh - 150px);
  overflow: hidden;
  
  /* 隐藏滚动条 */
  -ms-overflow-style: none; /* IE and Edge */
  scrollbar-width: none; /* Firefox */
  
  /* 隐藏滚动条 */
  &::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
  }
  
  .chat-box {
    .chat-item {
      margin-bottom: 20rpx;
      max-width: 75%;
      width: max-content;
      
      .msg-content {
        padding: 20rpx 30rpx;
        border-radius: 24rpx;
        line-height: 1.6;
        word-wrap: break-word;
        transition: all 0.2s ease;
      }
    }
    
    .user-msg {
      margin-left: auto;
      
      .msg-content {
        background-color: #ffffff;
        color: #333;
        border-radius: 24rpx 0 24rpx 24rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
        
        &:hover {
          box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.08);
          transform: translateX(-4rpx);
        }
      }
    }
    
    .ai-msg {
      margin-right: auto;
      
      .msg-content {
        background-color: #d4edda;
        color: #155724;
        border-radius: 0 24rpx 24rpx 24rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
        
        &:hover {
          box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.08);
          transform: translateX(4rpx);
        }
      }
    }
  }
}

/* 底部输入区域 */
.bottom-input {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 20rpx 30rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10; /* 确保在最上层 */
  
  .input-container {
    display: flex;
    align-items: center;
    gap: 20rpx;
    background: #f5f7fa;
    border-radius: 40rpx;
    padding: 15rpx 20rpx;
    
    &:focus-within {
      box-shadow: 0 0 0 2rpx rgba(74, 144, 226, 0.2);
    }
  }
  
  .input-field {
    flex: 1;
    max-width: 80%;
    height: 60rpx;
    background: transparent;
    border: none;
    outline: none;
    font-size: 28rpx;
    color: #333;
    padding: 0 20rpx;
    border-radius: 10rpx;
    min-width: 200rpx;
    transition: width 0.3s ease;
  }
  
  .send-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;
    padding: 0 25rpx;
    height: 60rpx;
    border-radius: 40rpx;
    background: #e0e0e0;
    color: #999;
    transition: all 0.3s ease;
    
    .send-text {
      font-size: 26rpx;
    }
    
    &.btn-active {
      background: linear-gradient(135deg, #4a90e2, #9b59b6);
      color: #fff;
      
      &:hover {
        transform: scale(1.05);
        box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.3);
      }
    }
  }
}

/* 刷新图标旋转动画 */
.rotate-animation {
  animation: rotate 0.5s linear;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>